<form id="addIdenManageForm" lay-filter="editGroupForm" class="layui-form model-form">
    <div class="model-form-body" style="max-height: 550px;">
        <div class="layui-form-item">
            <label class="layui-form-label">已关联目录:</label>
            <div  class="layui-input-block">
                <p class="title" id="hasDirMenu"></p>
            </div>
            <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" id="deleteDirMenu">解除关联</button>
        </div>
        <div class="layui-row">
            <div class="layui-col-md6">
                <div class="layui-card">
                    <div class="layui-card-header">目录分组</div>
                    <div class="layui-card-body">
                        <table class="layui-table" id="menuManage" lay-filter="menuManage"></table>
                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-card">
                    <div class="layui-card-header">目录</div>
                    <div class="layui-card-body">
                        <ul id="treeTbTree" class="ztree" ></ul>
                    </div>
                </div>
            </div>
        </div>

    </div>
    <div class="layui-form-item text-right model-form-footer">
        <button class="layui-btn layui-btn-primary layui-btn-sm" type="button" ew-event="closePageDialog">取消</button>
        <button class="layui-btn layui-btn-sm" lay-filter="addDirSubmit" lay-submit >确定</button>
    </div>
</form>
<script>
    var userInfo = getAuthority();
    var powerlist = JSON.parse(userInfo).permissions;
    /*自定义函数判断权限*/
    template.defaults.imports.hasPower = function(data){
        if(powerlist.includes(data)){
            return true;
        }
        return true;
    };
    layui.use(['layer', 'form', 'admin','tree','laydate','table'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var admin = layui.admin;
        var tree = layui.tree;
        var laydate = layui.laydate;
        var table = layui.table;
        var dirrid;//暂存目录id
        var menuGroup;//暂存选中目录分组
        var menuDetails;//暂存选中目录信息
        var parCode;//暂存上级code
        var par_id;//暂存上级id
        var IdentValueSelected = {};//分组值树选中节点
        var selectedTable = window.selectedTable ;

        var setting={//树设置
            identValueSetting:{//区划树设置
                edit: {
                    enable: true,
                    showRemoveBtn: false,
                    showRenameBtn: false,
                    drag: {
                        isCopy: true,
                        isMove: false,
                        prev: false,
                        next: false,
                        inner: false
                    }
                },
                data: {
                    key: {
                        children: "sub",
                        isParent: "isParent",
                        title: "name"
                    },
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    onExpand: onExpandIdentValueTree,
                    onClick: identValueOnClick
                },
                view: {
                    showIcon: true,
                    showLine: true
                }
            },
        }

        //获取权限方法
        if(userInfo){
            var access_token = localStorage.getExpire("access_token");
            var token_type = localStorage.getExpire("token_type");
            Authorization = token_type+" "+access_token;
            init();
        }

        // 表单提交事件
        form.on('submit(addDirSubmit)', function (data) {
            let req = {
                diriid:IdentValueSelected.id,
                dirrid:dirrid,
                metid:selectedTable.id
            }
            axios({
                method: 'POST',
                url:macroUrl.dirLink.addDir,
                data:$.param(req),
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success"){
                        layer.msg(response.data.message, {icon: 1});
                        getDirInfo();
                    }else{
                        layer.msg(response.data.message, {icon: 2});
                    }
                    layer.closeAll('loading');
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                });
            return false;
        });

        function init() {
            getMenuGroupList();

            //监听行单击事件
            table.on('row(menuManage)', function(obj){
                obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
                dirrid = obj.data.id
                menuDetails = '';
                menuGroup = obj.data
                $("#treeTbTree").empty();
                getTreeTable(obj.data,function (resArr) {
                    $.fn.zTree.init($("#treeTbTree"), setting.identValueSetting, resArr);
                });
            });

            form.render('select');
            form.render('checkbox');

            $("#deleteDirMenu").click(function () {
                deleteDirMenu();
            })
        }

        //查询已经关联的目录
        function getDirInfo() {
            var req={
                dirrid : dirrid,
                metid : selectedTable.id
            };
            axios.get(macroUrl.dirLink.dirInfo,{
                params: req,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success"){
                        var data = response.data.data;
                        diriid = data.diriid;
                        $("#hasDirMenu").text(data.name);
                    }
                })
                .catch(function (error) {
                    console.log(error)
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                });
        }

        //删除关联的目录
        function deleteDirMenu() {
            let req={
                diriid:diriid,
                metid:selectedTable.id
            }
            var formData = new FormData();
            formData.append("diriid",diriid);
            formData.append("metid",selectedTable.id);
            axios({
                method: 'DELETE',
                url:macroUrl.dirLink.deleteDir,
                data:formData,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        layer.msg("成功删除", {icon: 1});
                        $("#hasDirMenu").text('');
                    } else {
                        layer.msg(res.data.message, {icon: 2});
                    }
                    layer.closeAll('loading');
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                })
        }

        //获取目录分组列表信息
        function getMenuGroupList() {
            var req={
                current: 1,
                size: 100,
                name:''
            };
            axios.get(metadataUrl.menuManage.menuGroup.menuGroupList,{
                params: req,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success"){
                        var data = response.data.data;
                        renderMenuGroupTable(data);
                    }
                })
                .catch(function (error) {
                    console.log(error)
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                });
        }

        //渲染目录分组表格
        function renderMenuGroupTable(menuData) {
            table.render({
                elem: '#menuManage',
                size: 'sm', //小尺寸的表格
                data:menuData.records,
                page: false,
                cellMinWidth: 100,
                cols: [[
                    {type:'numbers', title: '序号'},
                    {field: 'name', align: 'center', title: '分组名称'},
                ]]
            });
            $("#treeTbTree").empty();
            dirrid = menuData.records[0].id;
            menuGroup = menuData.records[0]
            getTreeTable(menuData.records[0],function (resArr) {
                $.fn.zTree.init($("#treeTbTree"), setting.identValueSetting, resArr);
            });
            var divbox = $("#menuManage").next(".layui-table-view");
            $(divbox).find("table tr").eq(1).click();
            getDirInfo();
        }

        //获取树形目录的值
        function getTreeTable(obj,callback) {
            let parcode = obj.code?obj.code:'root';
            axios({
                method: 'get',
                url:metadataUrl.menuManage.menuTree.menuTreeList+'/'+ dirrid + '/' + parcode,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success"){
                        var data = response.data.data;
                        var resArr = [];
                        zhuanHuanTree(data,resArr);
                        parCode = '';
                        par_id = '';
                        menuDetails = {};
                        // IdentValueTree = resArr;
                        callback(resArr)

                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                });
        }

        //转换菜单集合数据
        function zhuanHuanTree(tdata,resData) {
            if(Array.isArray(tdata) && tdata.length>0){
                tdata.forEach(function(v,i){
                    var newValue=v.name;
                    resData[i]=v;
                    resData[i].title=newValue;
                    resData[i].icon = "";
                    resData[i].isParent = "true";
                    resData[i].sub = [];
                });
            }
        }

        //查询下方区划树的下级区划值（懒加载）
        function onExpandIdentValueTree(event, treeId, treeNode) {

            if(treeNode.sub.length>0||treeNode.hasChild=='0'){
                return false
            }
            getTreeTable(treeNode,function (resArr) {
                const treeObj = $.fn.zTree.getZTreeObj("treeTbTree");
                treeNode = treeObj.addNodes(treeNode,resArr);


            });
        }

        //选中分组值
        function identValueOnClick(event, treeId, treeNode){
            menuDetails = treeNode
            parCode = treeNode.code
            par_id = treeNode.id
            IdentValueSelected = treeNode;
        }

    });
</script>